<template>
	<div id="wrapper">
		<img id="logo" :src="logo" alt="electron-vue"/>
		<main>
			<div class="left-side">
        <span class="title">
          {{ t("welcome") }}
        </span>
				<system-information></system-information>
			</div>

			<div class="right-side">
				<div class="doc">
					<div class="title alt">
						{{ t("buttonTips") }}
					</div>
					<button class="btu" @click="open()">
						{{ t("buttons.console") }}
					</button>
					<button class="btu" @click="CheckUpdate('one')">
						{{ t("buttons.checkUpdate") }}
					</button>
					<button class="btu" @click="CheckUpdate('two')">
						{{ t("buttons.checkUpdate2") }}
					</button>
				</div>
				<div class="doc">
					<button class="btu" @click="CheckUpdate('three')">
						{{ t("buttons.checkUpdateInc") }}
					</button>
					<button class="btu" @click="CheckUpdate('threetest')">
						{{ t("buttons.incrementalUpdateTest") }}
					</button>
					<button class="btu" @click="CheckUpdate('four')">
						{{ t("buttons.ForcedUpdate") }}
					</button>
				</div>
				<div class="doc">
					<button class="btu" @click="StartServer">
						{{ t("buttons.startServer") }}
					</button>
					<button class="btu" @click="StopServer">
						{{ t("buttons.stopServer") }}
					</button>
					<button class="btu" @click="getMessage">
						{{ t("buttons.viewMessage") }}
					</button>
					<button class="btu" @click="crash">
						{{ t("buttons.simulatedCrash") }}
					</button>
					<button class="btu" @click="openPreloadWindow">
						{{ t("buttons.openPreloadWindow") }}
					</button>
				</div>
				<div class="doc">
					<button class="btu" @click="openNewWin">
						{{ t("buttons.openNewWindow") }}
					</button>
					<button class="btu" @click="changeLanguage">
						{{ t("buttons.changeLanguage") }}
					</button>
					<button class="btu" @click="printDemo">
						{{ t("buttons.printDemo") }}
					</button>
					<button class="btu" @click="browserDemo">
						{{ t("buttons.browser") }}
					</button>
					<button class="btu" @click="goTo('/403')">
						{{ t("buttons.403") }}
					</button>
					<button class="btu" @click="goTo('/Layout')">
						{{ t("buttons.layout") }}
					</button>
					<button v-if="showInMyComputer !== 0" class="btu" @click="setShowOnMyComputer">
						{{ t(showInMyComputer === 1 ? "buttons.hideOnMyComputer" : "buttons.showOnMyComputer") }}
					</button>
				</div>
				<div class="doc">
					<div class="title alt">
						接收消息：{{ msgTip }}
					</div>
				</div>
				<div class="doc">
					<div class="title alt">
						sqlite数据库操作结果：{{ sqliteDemoRes }}
					</div>
				</div>
			</div>
		</main>
		<div v-show="dialogVisible" class="doc">
			<div class="title alt">
				更新状态：完成度 {{ percentage }}% ；反馈信息： {{ progressTip }}
			</div>
		</div>
		<update-progress v-model="showForcedUpdate"/>
	</div>
</template>

<script lang="ts" setup>
import SystemInformation from "@/components/LandingPage/SystemInformation.vue";
import UpdateProgress from "@/components/updataProgress/index.vue";
import {message} from "@renderer/api/demo";
import logo from "@renderer/assets/logo.png";
import {Ref, ref, UnwrapRef} from "vue";
import {i18n, setLanguage} from "@/i18n";
import {useI18n} from "vue-i18n";
import {invoke, IpcChannel, vueListen} from "@/utils/ipcRenderer";
import {useStoreTest} from "@store/test";
import {ProgressInfo} from "electron-updater";

const storeTemplate = useStoreTest();

//测试让主进程添加一个文件
const testdata = "我是测试要添加的内容" + Date.now();
console.log("准备写入的内容：", testdata);
invoke(IpcChannel.FileWrite, {filename: "test-453.txt", data: testdata}).then((r) => {
	console.log('文件添加结果：', r);
	invoke(IpcChannel.FileRead, {filename: "test-453.txt"}).then((r) => {
		console.log("文件读取结果：", r.data);
	})
});

// 测试操作sqlite数据库
const sql = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
const params = ['testSqlite'];
let sqliteDemoRes: Ref<string> = ref("");
invoke(IpcChannel.SqlRun, {sql: sql, params: params}).then((r) => {
	console.log('sqlite数据库操作结果：', r);
	sqliteDemoRes.value = r.name;
})

const {t} = useI18n();

console.log(`storeTemplate`, storeTemplate.getTest);
console.log(`storeTemplate`, storeTemplate.getTest1);
console.log(`storeTemplate`, storeTemplate.$state.testData);
console.log(__CONFIG__)

setTimeout(() => {
	storeTemplate.TEST_ACTION("测试延迟1s修改storeTemplate-getTest1");
	console.log(`storeTemplate`, storeTemplate.getTest1);
}, 1000);

const ipcRenderer = window.ipcRenderer;
const shell = window.shell;

let percentage = ref(0);
let colors: Ref<UnwrapRef<({ color: string; percentage: number })[] | string>> = ref([
	{color: "#f56c6c", percentage: 20},
	{color: "#e6a23c", percentage: 40},
	{color: "#6f7ad3", percentage: 60},
	{color: "#1989fa", percentage: 80},
	{color: "#5cb87a", percentage: 100},
]);
// let colors: Ref<ColorInfo[]> | Ref<string> = ref([
//   { color: "#f56c6c", percentage: 20 },
//   { color: "#e6a23c", percentage: 40 },
//   { color: "#6f7ad3", percentage: 60 },
//   { color: "#1989fa", percentage: 80 },
//   { color: "#5cb87a", percentage: 100 },
// ] || "#0095f6");

let dialogVisible = ref(false);
let msgTip: Ref<string> = ref("未接收消息");
let progressStatus: Ref<string> = ref("");
let progressTip: Ref<string> = ref("尚未开始");
let showForcedUpdate = ref(false);
let filePath = ref("");
let updateStatus = ref("");

let elPageSize = ref(100);
let elCPage = ref(1);

invoke(IpcChannel.GetStaticPath).then((res) => {
	console.log("staticPath", res);
})


function changeLanguage() {
	setLanguage(i18n.global.locale.value === "zh-cn" ? "en" : "zh-cn");
}

function printDemo() {
	invoke(IpcChannel.OpenPrintDemoWindow);
}

function browserDemo() {
	invoke(IpcChannel.OpenBrowserDemoWindow);
}

function handleSizeChange(val: number) {
	elPageSize.value = val;
}

function handleCurrentChange(val: number) {
	elCPage.value = val;
}

/**
 * 模拟进程崩溃
 */
function crash() {
	window.crash.start();
}

function openNewWin() {
	let data = {
		url: "/form/index",
	};
	invoke(IpcChannel.OpenWin, data);
}

function goTo(page: string) {
	let data = {
		url: page,
	};
	invoke(IpcChannel.OpenWin, data);
}

function getMessage() {
	message().then((res) => {
		msgTip.value = res.data;
	});
}

function StopServer() {
	invoke(IpcChannel.StopServer).then((res) => {
		msgTip.value = "服务器已关闭";
	});
}

function StartServer() {
	invoke(IpcChannel.StartServer).then((res) => {
		if (res) {
			msgTip.value = res;
		}
	});
}

// 获取electron方法
function open() {
}

function CheckUpdate(data) {
	switch (data) {
		case "one":
			invoke(IpcChannel.CheckUpdate);
			break;
		case "two":
			// TODO 测试链接
			console.log('test Url')
			// ipcRenderer
			//   .invoke(
			//     "start-download",
			//     "https://az764295.vo.msecnd.net/stable/6261075646f055b99068d3688932416f2346dd3b/VSCodeUserSetup-x64-1.73.1.exe"
			//   )
			//   .then(() => {
			//     dialogVisible.value = true;
			//   });
			break;
		case "three":
			invoke(IpcChannel.HotUpdate);
			break;
		case "threetest":
			alert("更新后再次点击没有提示");
			invoke(IpcChannel.HotUpdateTest);
			break;
		case "four":
			showForcedUpdate.value = true;
			break;
		default:
			break;
	}
}

function openPreloadWindow() {
	const res = confirm(t("home.openPreloadWindowError.content"));
	if (res) {
		console.log("选择确认，执行回调操作");
	}
}

function handleClose() {
	dialogVisible.value = false;
}

const showInMyComputer = ref(0) // 0-不显示 1-开启 -1-关闭
if (process.platform === 'win32') {
	invoke(IpcChannel.CheckShowOnMyComputer).then(bool => {
		showInMyComputer.value = bool ? 1 : -1
	})
}

function setShowOnMyComputer() {
	invoke(IpcChannel.SetShowOnMyComputer, showInMyComputer.value === -1).then(success => {
		if (success) {
			showInMyComputer.value = showInMyComputer.value === -1 ? 1 : -1
		}
	})
}

vueListen(IpcChannel.DownloadProgress, (event, arg) => {
	console.log(arg);
	percentage.value = arg;
});


vueListen(IpcChannel.DownloadError, (event, arg) => {
	if (arg) {
		progressStatus.value = "exception";
		progressTip.value = "下载错误";
		percentage.value = 40;
		colors.value = "#d81e06";
	}
});
vueListen(IpcChannel.DownloadPaused, (event, arg) => {
	if (arg) {
		progressStatus.value = "warning";
		const res = confirm("下载由于未知原因被中断！");
		if (!res) {
			invoke(IpcChannel.StartDownload, "");
		}
	}
});
vueListen(IpcChannel.DownloadDone, (event, age) => {
	filePath.value = age.filePath;
	progressStatus.value = "success";
	const res = confirm("更新下载完成！");
	if (res) {
		shell.openPath(filePath.value);
	}
});
// electron-updater的更新监听
vueListen(IpcChannel.UpdateMsg, (event, args) => {
	switch (args.state) {
		case -1:
			const msgdata = {
				title: "发生错误",
				message: args.msg as string,
			};
			dialogVisible.value = false;
			progressTip.value = msgdata.title;
			invoke(IpcChannel.OpenErrorbox, msgdata);
			break;
		case 0:
			progressTip.value = "正在检查更新";
			break;
		case 1:
			progressTip.value = "已检查到新版本，开始下载";
			dialogVisible.value = true;
			break;
		case 2:
			progressTip.value = "暂无新版本";
			break;
		case 3:
			percentage.value = Number((args.msg as ProgressInfo).percent.toFixed(1));
			break;
		case 4:
			progressStatus.value = "success";
			alert("更新下载完成！");
			invoke(IpcChannel.ConfirmUpdate);
			break;
		default:
			break;
	}
});
vueListen(IpcChannel.HotUpdateStatus, (event, msg) => {
	switch (msg.status) {
		case "downloading":
			progressTip.value = "正在下载";
			break;
		case "moving":
			progressTip.value = "正在移动文件";
			break;
		case "finished":
			progressTip.value = "成功，请重启";
			break;
		case "failed":
			progressTip.value = msg.message;
			break;
		default:
			break;
	}
	console.log(msg);
	updateStatus.value = msg.status;
});

</script>

<style>
* {
	box-sizing: border-box;
	margin: 0;
	padding: 0;
}

body {
	font-family: "Source Sans Pro", sans-serif;
}

#wrapper {
	padding: 114px 80px;
}

#logo {
	height: auto;
	margin-bottom: 20px;
	width: 420px;
}

main {
	display: flex;
	justify-content: space-between;
}

main > div {
	flex-basis: 50%;
}

.left-side {
	display: flex;
	flex-direction: column;
}

.welcome {
	color: #555;
	font-size: 23px;
	margin-bottom: 10px;
}

.title {
	color: #2c3e50;
	font-size: 20px;
	font-weight: bold;
	margin-bottom: 6px;
}

.title.alt {
	font-size: 18px;
	margin-bottom: 10px;
}

.doc {
	margin-bottom: 10px;
}

.doc p {
	color: black;
	margin-bottom: 10px;
}

.btu {
	display: inline-block;
	line-height: 1;
	white-space: nowrap;
	cursor: pointer;
	color: #fff;
	background-color: #409eff;
	border: 1px solid #409eff;
	text-align: center;
	box-sizing: border-box;
	outline: none;
	transition: .1s;
	font-weight: 500;
	padding: 12px 20px;
	font-size: 14px;
	border-radius: 4px;
}

.btu:focus,
.btu:hover {
	background: #3a8ee6;
	border-color: #3a8ee6;
}

.doc > button {
	margin-left: 0;
}

.doc > button {
	margin-top: 10px;
	margin-right: 10px;
}

.content {
	text-align: center;
}
</style>
